import type { ModuleFormat } from 'rollup'

export const compluginDirnameIdentifier = '__COMPLUGIN_DIRNAME__'

const _normalizeDirnameHelper = `
  function __complugin_normalize_dirname(url) {
    url = url.replace(/(^file:\\/\\/\\/)|([#\\?].*?$)/gi, '');
    if (!url.endsWith('/')) {
      url = url + '/..';
    }
    return url;
  }
`

export const normalizeDirnameHelperModule =
  _normalizeDirnameHelper +
  `
  export { __complugin_normalize_dirname }
`

const _commonjsDirnameHelper = `
  if (typeof __dirname === 'string') {
    return __dirname;
  }
`

const _esmDirnameHelper = `
  let import_meta_url;
  if (typeof (import_meta_url = import.meta.url) === 'string') {
    return __complugin_normalize_dirname(import_meta_url);
  }
`

const _amdDirnameHelper = `
  if (typeof define === 'function' && define.amd) {
    return __complugin_normalize_dirname((new URL(require.toUrl('.'), document.baseURI)).href);
  }
`

const _scriptDirnameHelper = `
  if (typeof document === 'object') {
    let doc = document;
    let tmp;

    if (typeof (tmp = doc.currentScript?.src) === 'string') {
      return __complugin_normalize_dirname(tmp.src);
    }
  }
`

const unknownDirnameHelper = `
  return ''
`

export const getCompluginDirnameExp = (format: ModuleFormat, normalizeHelper = true) => {
  const normalizeDirnameHelper = normalizeHelper ? _normalizeDirnameHelper : ''
  switch (format.split('-')[0]) {
    case 'es':
    case 'esm':
    case 'module':
      return `/* @__PURE__ */ (function(){${normalizeDirnameHelper}${_esmDirnameHelper}${unknownDirnameHelper}})()`
    case 'cjs':
    case 'commonjs':
    case 'commonjs2':
      return `/* @__PURE__ */ (function(){${_commonjsDirnameHelper}${unknownDirnameHelper}})()`
    case 'amd':
      return `/* @__PURE__ */ (function(){${normalizeDirnameHelper}${_amdDirnameHelper}${unknownDirnameHelper}})()`
    case 'umd':
      return `/* @__PURE__ */ (function(){${normalizeDirnameHelper}${_amdDirnameHelper}${_commonjsDirnameHelper}${_scriptDirnameHelper}${unknownDirnameHelper}})()`
    default:
      return `/* @__PURE__ */ (function(){${normalizeDirnameHelper}${_scriptDirnameHelper}${unknownDirnameHelper}})()`
  }
}
